using System;
using System.Windows.Forms;
using InfoExpress.HIV.WinApp.Utils;
using InfoExpress.HIV.WinApp.Business;
using InfoExpress.WinApp.Utils;

namespace InfoExpress.HIV.WinApp.Popups
{
  public partial class FrmLogin : DevExpress.XtraEditors.XtraForm
  {
    public FrmLogin()
    {
      InitializeComponent();
    }

    #region Event Handlers

    private void btnOK_Click(object sender, EventArgs e)
    {
      if (dxValidationProvider.Validate())
      {
        MainFormUtils.StartProgress();
        ToggleEditControls(false);
        MainFormUtils.SetBusyStatus(Constants.StatusLogin);

        bwLogin.RunWorkerAsync();
      }
    }

    #region Worker Background

    private void bwLogin_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
      try
      {
        e.Result = Permission.GetPermission(txtUsername.Text, txtPassword.Text);
      }
      catch (Exception ex)
      {
        e.Result = ex;
        Logger.LogCritical("FrmLogin::btnOK_Click", ex, "General", null);
      }
    }

    private void bwLogin_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
      Permission permission = e.Result as Permission;

      ToggleEditControls(true);
      Cursor = Cursors.Default;
      MainFormUtils.StopProgress();

      if (permission != null)
      {
        //Only one place set valid Permission into GlobalCache
        GlobalCache.Permission = permission;

        MainFormUtils.SetDefaultStatus();
        DialogResult = DialogResult.OK;
        Close();
      }
      else if (e.Result is Exception)
      {
        MainFormUtils.SetDoneStatus(Constants.StatusLoginFailed);
        UIUtils.ShowErrorMessage(Constants.MsgErrLogin_001);
      }
      else
      {
        MainFormUtils.SetDefaultStatus();
        UIUtils.ShowWarningMessage(Constants.MsgInfoLogin_002);
      }
    }

    #endregion

    #endregion

    #region Helper Methods

    private void ToggleEditControls(bool enabled)
    {
      btnOK.Enabled = enabled;
      txtPassword.Enabled = enabled;
      txtUsername.Enabled = enabled;
    }

    #endregion
  }
}